#include <iostream>
#include <cstring>
#include <unistd.h>
#include <string>
bool GetQueryString(std::string &query_string)
{
   std ::string method = getenv("METHOD");
   if (method == "GET")
   {
      query_string = getenv("QUERY_STRING");
      return true;
   }
   else if ("POST" == method)
   {
      int length = atoi(getenv("CONTENT-LENGTH"));
      char ch;
      while (length)
      {
         ssize_t n = read(0, &ch, 1);
         if (n > 0)
         {
            query_string += ch;
            --length;
         }
      }
      return true;
   }
return false;

}
void CutString(const std::string&in,std::string&out1,std::string&out2,const std::string&sep)
{
  size_t pos=  in.find(sep);
  if(pos!=std::string::npos)
  {
   out1=in.substr(0,pos);
   out2=in.substr(pos+sep.size());
  }
}
int main()
{
   std::string querystring;
   bool flag = GetQueryString(querystring);
   if (!flag)
      exit(404);
   // 获取参数成功，解析字符串 -> a=100&b=200 -> a=100 ;b=200;
   std::string s1;
   std::string s2;
   CutString(querystring,s1,s2,"&");
   // a=100 -> a : 100 
   std::string name1;
   std::string value1;
   std::string name2;
   std::string value2;
   CutString(s1,name1,value1,"=");
   CutString(s2,name2,value2,"=");
   std::cout<<name1<<":"<<value1<<std::endl;
   std::cout<<name2<<":"<<value2<<std::endl;
   int x=atoi(value1.c_str());
   int y=atoi(value2.c_str());
//对请求发来的数据进行处理（计算），获取存储（注册）、搜索等
std::cout<<"<html><body><h1>"<<
value1<<"+"<<value2<<"="<<x+y<<"</h1>"<<
"<h2>"<<value1<<"-"<<value2<<"="<<x-y<<"</h2>"<<
"<h3>"<<value1<<"*"<<value2<<"="<<x*y<<"</h3>"<<
"<h4>"<<value1<<"/"<<value2<<"="<<x/y<<"</h3>"<<

"</body></html>";


//debug
   std::cerr<<name1<<":"<<value1<<std::endl;
   std::cerr<<name2<<":"<<value2<<std::endl;
   return 0;
}